/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.domain.FhInfoData;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.FhInfoDataRepository;
import me.zhengjie.service.FhInfoDataService;
import me.zhengjie.service.dto.FhInfoDataDto;
import me.zhengjie.service.dto.FhInfoDataQueryCriteria;
import me.zhengjie.service.mapstruct.FhInfoDataMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author admin
* @date 2020-07-23
**/
@Service
@RequiredArgsConstructor
public class FhInfoDataServiceImpl implements FhInfoDataService {

    private final FhInfoDataRepository fhInfoDataRepository;
    private final FhInfoDataMapper fhInfoDataMapper;

    @Override
    public Map<String,Object> queryAll(FhInfoDataQueryCriteria criteria, Pageable pageable){
        Page<FhInfoData> page = fhInfoDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fhInfoDataMapper::toDto));
    }

    @Override
    public List<FhInfoDataDto> queryAll(FhInfoDataQueryCriteria criteria){
        return fhInfoDataMapper.toDto(fhInfoDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public FhInfoDataDto findById(Integer id) {
        FhInfoData fhInfoData = fhInfoDataRepository.findById(id).orElseGet(FhInfoData::new);
        ValidationUtil.isNull(fhInfoData.getId(),"FhInfoData","id",id);
        return fhInfoDataMapper.toDto(fhInfoData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FhInfoDataDto create(FhInfoData resources) {
        if (fhInfoDataRepository.findByYearAndAndMonth(resources.getYear(),resources.getMonth()) != null) {
            throw new BadRequestException(resources.getYear()+"-"+resources.getMonth()+"数据已存在");
        }
        return fhInfoDataMapper.toDto(fhInfoDataRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FhInfoData resources) {
        FhInfoData fhInfoData = fhInfoDataRepository.findById(resources.getId()).orElseGet(FhInfoData::new);
        ValidationUtil.isNull( fhInfoData.getId(),"FhInfoData","id",resources.getId());
        fhInfoData.copy(resources);
        fhInfoDataRepository.save(fhInfoData);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            fhInfoDataRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<FhInfoDataDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FhInfoDataDto fhInfoData : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("出租率", fhInfoData.getRentRate());
            map.put("产值", fhInfoData.getValue());
            map.put("税收", fhInfoData.getRevenue());
            map.put("更新时间", fhInfoData.getUpdateTime());
            map.put("年", fhInfoData.getYear());
            map.put("月", fhInfoData.getMonth());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String,Double> totalByYear(Integer year){
        List<FhInfoData> fhInfoDataList = fhInfoDataRepository.findAllByYear(year);
        Map<String,Double> resultMap = new HashMap<>();
        resultMap.put("total_rent_rate",0.0);
        resultMap.put("total_value",0.0);
        resultMap.put("total_revenue",0.0);
        fhInfoDataList.stream().forEach(fhInfoData->{
            resultMap.put("total_value",resultMap.get("total_value")+ fhInfoData.getValue());
            resultMap.put("total_rent_rate",resultMap.get("total_rent_rate")+ fhInfoData.getRentRate().intValue());
            resultMap.put("total_revenue",resultMap.get("total_revenue")+ fhInfoData.getRevenue());
        });
        resultMap.put("total_rent_rate",resultMap.get("total_rent_rate")/fhInfoDataList.size());
        return resultMap;
    }
}